package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author
 * @since 2024-05-22
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    public CacheManager cacheManager;

    @Autowired
    public ICategoryService categoryService;

    @CacheEvict(value = "setmealCache" ,allEntries = true)
    @Transactional
    @Override
    public R<String> saveSeatmeal(SetmealDto setmealDto) {
        //1.添加数据到套餐表中
        save(setmealDto);
        //1.1套餐存入回显id给对象
        Long id = setmealDto.getId();
        //2.将setmealDto中的套餐菜品关联数据添加到setMealDish表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> list = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(id);
            return setmealDish;
        }).collect(Collectors.toList());
        Db.saveBatch(list);
        return R.success("菜品添加成功!");
    }

    @Override
    public R<Page> pageQuery(Integer page, Integer pageSize, String name) {
        //创建分页对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null,Setmeal::getName,name);
        wrapper.orderByDesc(Setmeal::getUpdateTime);

        //进行分页查询
        this.page(setmealPage,wrapper);

        Page<SetmealDto> setmealDtoPage = new Page<>();

        //拷贝对象(忽略拷贝records属性,另行处理)
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");

        //处理records:List<Setmeal> setmealList ->List<SetmealDto> setmealDtoList
        List<Setmeal> setmealList = setmealPage.getRecords();
        List<SetmealDto> setmealDtoList = setmealList.stream().map(setmeal -> {
            Long categoryId = setmeal.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            setmealDto.setCategoryName(categoryName);
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);
    }


    @Override
    public R<SetmealDto> queryByid(Long id) {
        //1.通过id获取setmeal表中的记录
        Setmeal setmeal = getById(id);
        //2.根据根据setmeal_id即参数id查询setmeal_dish表中的符合的记录
        List<SetmealDish> setmealDishes = Db.lambdaQuery(SetmealDish.class)
                .eq(SetmealDish::getSetmealId, id)
                .list();
        //3.将查询到的两个数据赋值给setmealDto
        SetmealDto setmealDto = new SetmealDto();
        setmealDto.setSetmealDishes(setmealDishes);
        BeanUtils.copyProperties(setmeal,setmealDto);
        return R.success(setmealDto);
    }

    @Override
    public R<String> updateStatus(Integer status, Long[] id) {
        if(status==1){
            lambdaUpdate().setSql("status = 1").in(Setmeal::getId,id).update();
            return R.success("状态修改成功");
        }else if(status==0){
            lambdaUpdate().setSql("status = 0").in(Setmeal::getId,id).update();
            return R.success("状态修改成功");
        }else {
            return R.error("修改失败");
        }
    }

    /**
     * @CacheEvict 将一条或多条数据从缓存中删除
     * allEntries = true 结合 value = "setmealCache" 表示删除"setmealCache"该名称分类下的所有缓存数据
     */
    @Override
    @CacheEvict(value = "setmealCache" ,allEntries = true)
    @Transactional
    public R<String> deleteSetmealById(List<Long> id) {
        //1.判断套餐状态是否起售,起售则返回"删除失败"
        Long count = lambdaQuery().in(Setmeal::getId, id).eq(Setmeal::getStatus, 1).count();
        if(count>0){
            return R.error("删除失败");
        }
        //2.删除所有id包含在集合内的数据
        removeByIds(id);
        //3.删除setmealDish表内字段setmeal_Id内有包含集合内id数据的记录
        Db.lambdaUpdate(SetmealDish.class).in(SetmealDish::getSetmealId,id).remove();
        return R.success("删除套餐成功");
    }

    /**
     * @Cacheable 执行方法前先查看缓存中是否有数据 有则直接返回数据;没有数据,调用方法并将返回值放到缓存中
     * value = "setmealCache" 表示缓存的名称为:setmealCache,每个缓存名称下可以有多个key
     * key:缓存的key
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status",unless = "#result == null ")
    @Override
    public R<List<Setmeal>> getSetmealList(Setmeal setmeal) {
        List<Setmeal> setmealList = lambdaQuery()
                .eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus())
                .list();

        return R.success(setmealList);
    }
}
